import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createPage, ajax, base, toast, promptBox, getMultiLang } from 'nc-lightapp-front';
import ReferLoader from '../../../public/ReferLoader/index.js';
import {accbookRefcode} from '../../../public/ReferLoader/constants.js';
import getDefaultAccountBook from '../../../public/components/getDefaultAccountBook'
import { onButtonClick, initTemplate } from '../events';
import HeaderArea from '../../../public/components/HeaderArea';
import './index.less';
class DocMain extends Component {
	constructor(props) {
		super(props);
		this.state = {
			accountingbook: {
				refname: '',
				refpk: ''
			},
			json: {}
		};
		this.tableId = 'selfDoc'
		props.use.editTable(this.tableId);
	}
	componentWillMount() {
		// let callback= (json) => {
		// 	this.setState({
		// 		json:json,
		// 	},()=>{		  
		// 		initTemplate.call(this, this.props);
		// 		//获取默认账簿
		// 		// this.queryAppcontext()
		// 	})
		// }
		// getMultiLang({moduleId:'20020SDTPDPAGE',domainName:'gl',currentLocale:'simpchn',callback});
		// this.props.button.setButtonVisible([ 'save', 'cancel' ], false)
	}
	componentDidMount() {
		let appcode = this.props.getSearchParam("c");
		let callback= (json) => {
			//获取默认账簿
			getDefaultAccountBook(appcode).then((defaultAccouontBook) => {
				let accountingbook = {
					refname: defaultAccouontBook.display,
					refpk: defaultAccouontBook.value
				}
				this.setState({
					accountingbook,
					json
				},()=>{
					initTemplate.call(this, this.props);
					if (accountingbook.refpk) {
						this.getInitData(accountingbook);
					}else{
						this.props.button.setButtonDisabled(['add','update','delete'], true);
					}
				});
			})
		}
		getMultiLang({moduleId:'20020SDTPDPAGE',domainName:'gl',currentLocale:'simpchn',callback});
		this.props.button.setButtonVisible([ 'save', 'cancel' ], false)
	}
	
	//获取初始化数据
	getInitData = (pk,callback) => {
		let url = '/nccloud/gl/voucher/queryTransProject.do';
		let accountingbook = this.state.accountingbook;
		let pk_accountingbook = pk&&pk.refpk || accountingbook&&accountingbook.refpk;
		if(!pk_accountingbook) return;
		let data = {
			pk_accountingbook: pk ? pk.refpk : accountingbook.refpk
		};
		ajax({
			url,
			data,
			success: (response) => {
				const { data, error, success } = response;
				if (success) {
					if(data){
						let rows = this.ajaxDataToModuleData(data)
						this.props.editTable.setTableData(this.tableId, {areacode: this.tableId, rows:rows});
						this.updateBtnState()
					} else {
						this.props.editTable.setTableData(this.tableId, {rows: []});
					}
					if(callback){
						callback()
					}			
				} else {
				}
			}
		});
	};
	// 接口返回数据转换为Table需要的数据格式
	ajaxDataToModuleData = (data) => {
		let rows = []
		data.forEach((item, index) => {
			let obj = {}
			Object.keys(item).map((key) => {
				obj[key] = { 'value': item[key] };
				return null;
			})
			rows[index] = {
				status: obj.status.value,
				values: obj
			}
			delete obj.status
		});
		return rows
	}
	// 切换核算账簿
	onBookChange = (v) =>{
		let page = this;
		if(v && v.refpk){
			page.setState({accountingbook:v}, () => {this.getInitData(v)});
		}else{
			//删除账簿后清空表体，修改按钮状态
			page.props.editTable.setTableData(page.tableId, {rows: []});
			page.setState({accountingbook:v }, () => {page.updateBtnState()});
		}
	}
	// 更新页面状态(浏览态/编辑态)
	setPageStatus = (pageStatus) => {
		let isVisible = pageStatus === 'browse' ? true : false
		pageStatus != 'add' && this.props.editTable.setStatus(this.tableId, pageStatus);
		this.props.button.setButtonVisible([ 'save', 'cancel' ], !isVisible)
		this.props.button.setButtonVisible([ 'update', 'refresh' ], isVisible)
		this.props.button.setMainButton(['add'], isVisible)
	}

	/**
	 * 首次加载页面或切换核算账簿时调用
	 */
	updateBtnState = () => {
		let addDisabled = this.state.accountingbook && this.state.accountingbook.refpk ? false : true
		let updateDisabled = this.props.editTable.getNumberOfRows(this.tableId) > 0 ? false : true
		this.props.button.setButtonDisabled({add: addDisabled, update: updateDisabled})
	}
	// 切换复选框(控制删除按钮状态)
	selectedChange = () =>{
		let deleteDisabled = this.props.editTable.getCheckedRows(this.tableId).length > 0 ? false : true
		this.props.button.setButtonDisabled(['delete'], deleteDisabled);  
    }
	// 新增
	handleAdd = () => {
		let { accountingbook } = this.state;
		let defaultValue = {
			pk_accountingbook: {
				value: accountingbook.refpk
			}
		} // 默认值,后端需要
		let index = this.props.editTable.getNumberOfRows(this.tableId);
		this.props.editTable.addRow(this.tableId, index, true, defaultValue);
		this.setPageStatus('add')
		
	};
	// 修改
	handleRepair = () => {
		this.setPageStatus('edit')
	}
	//删除
	handleDel = () => {
		let { accountingbook } = this.state;		
		let checkedData = this.props.editTable.getCheckedRows(this.tableId); //获取选中行数据
		let pk_transprojs = [], indexArr = [];
		checkedData.map((item)=>{
			item.data.values.m_pk_transproject && pk_transprojs.push(item.data.values.m_pk_transproject.value)
			indexArr.push(item.index)
		})
		let data = {
			pk_accountingbook: accountingbook.refpk,
			pk_transprojs: pk_transprojs //方案主键数组
		};
		this.del(data, (res) => {
			if (res.success) {
				toast({ content: this.state.json['20020SDTPDPAGE-000001'], color: 'success' });/* 国际化处理： 删除成功*/
				this.props.editTable.deleteTableRowsByIndex(this.tableId, indexArr, true)
				setTimeout(this.updateBtnState(), 0)
			}
		});
	};	
	del = (data, callback) => {
		let url = '/nccloud/gl/voucher/delTransProject.do';
		promptBox({
			color : 'warning',
			title: this.state.json['20020SDTPDPAGE-000010'], /* 国际化处理： 删除*/
			content : this.state.json['20020SDTPDPAGE-000011'],/* 国际化处理： 确定要删除所选数据吗？*/
			beSureBtnClick : () => {
				this.myajax(url, data, callback);
			}
		});
	}
	myajax = (url, data, callback) =>{
		ajax({
			url, data,
			success: (res) => {
				if(callback){
					callback(res);
				}
			}
		});
	}
	// 模版数据转换成保存接口需要的数据格式
	moduleDataToAjaxData = (tempData) => {
		return tempData.rows.map((item)=>{
			let obj = {}
			Object.keys(item.values).map((key) => {
				obj[key] = item.values[key].value;
				return null;
			})
			return obj
		})
	}
	//保
	存
	handleSave = () => {
		let url = '/nccloud/gl/voucher/saveTransProject.do';
		let tempData = this.props.editTable.getAllData(this.tableId);
		let isChecked = this.props.editTable.checkRequired(this.tableId, tempData.rows)
		let data = isChecked && this.moduleDataToAjaxData(tempData);
		if(isChecked){
			ajax({
				url,
				data,
				success: (res) => {
					const { data, error, success } = res;
					if (success) {
						toast({ content: this.state.json['20020SDTPDPAGE-000000'], color: 'success' });/* 国际化处理： 保存成功*/
						this.getInitData();
						this.setPageStatus('browse')
					} else {
					}
				}
			});
		}
	};
	//取消
	handleCancel = () => {
		this.props.editTable.cancelEdit(this.tableId, this.setPageStatus('browse'))
	};
	//刷新
	reFresh = () => {
		this.getInitData('',()=>{
			toast({ title: this.state.json['20020SDTPDPAGE-000012'], color: 'success' });/* 国际化处理： 刷新成功*/
		})
	}
	render() {
		let { createEditTable } = this.props.editTable;
		let referDisabled = this.props.editTable.getStatus(this.tableId) != 'browse' ? true : false
		let defaultValue = { refname: this.state.accountingbook.refname, refpk: this.state.accountingbook.refpk }
		let bookref = (<div className='main-org'>
			<ReferLoader
				tag = 'test'
				fieldid = 'accountingbook'
				showStar = {true}
				refcode = {accbookRefcode}
				value = {defaultValue}
				disabled =  {referDisabled}
				isMultiSelectedEnabled = {false}
				showGroup = {false}
				showInCludeChildren = {false}
				disabledDataShow = {true}
				queryCondition = {() => {
					return {
						"TreeRefActionExt": 'nccloud.web.gl.ref.AccountBookRefSqlBuilder',
						"appcode": this.props.getSearchParam('c')
					}
				}}
				onChange= {(v) => {
					this.onBookChange(v);
				}}
			/>
		</div>)
		return (
			<div className="nc-single-table selfDoc">
				<HeaderArea 
					title = {this.props.getSearchParam('n')}
					showBorderBottom = {false}
					searchContent = {bookref}
					btnContent = {this.props.button.createButtonApp({
						area: 'page_header',
						onButtonClick: onButtonClick.bind(this),
					})}
				/>
				<div className="nc-singleTable-table-area">
					{/* 表格*/}
					{createEditTable(this.tableId, {
						selectedChange: ()=>{this.selectedChange()},
						showIndex: true,
						showCheck: true,
						adaptionHeight: true //自适应高度，占满屏幕
					})}
                </div>
			</div>
		);
	}
}
DocMain = createPage({})(DocMain);
ReactDOM.render(<DocMain />, document.querySelector('#app'));
